<template>
  <div>
      <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/admin/link/list">友链管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>友链列表</el-breadcrumb-item>
    </el-breadcrumb><br/>

      友链名称
      <el-input placeholder="请输入友链名"
                v-model="input.name"
                clearable
                @input="listLinksByCondition()"
                style="width: 200px;margin: 0px 10px 0 5px"></el-input>
      <!--通过类名查询数据-->
      <el-button type="primary" icon="el-icon-search" @click="listLinksByCondition">查找</el-button><br/><br/>

    <!--按钮：创建类别-->
    <el-button type="primary" round @click="cardPopup(0)">创建友链</el-button>

    <!--按钮：批量删除-->
    <el-button type="danger" round @click="handleDeleteList()">批量删除</el-button><br/><br/>



<template>
    <!--类别列表-->
    <el-table
        :data="tableData"
        ref="multipleTable"
        border
        style="width: 100%"
        @selection-change="handleSelectChange"
        >
      <el-table-column
          type="selection"
          width="50">
      </el-table-column>
      <el-table-column prop="id" label="序号" width="180"></el-table-column>
      <el-table-column prop="name" label="友链名" width="150"></el-table-column>
      <el-table-column prop="url" label="友链地址" width="180"></el-table-column>
      <el-table-column prop="gmtCreate" label="添加时间" width="180"></el-table-column>

      <!--添加或修改分类-->
      <el-table-column label="操作">
        <template slot-scope="scope" style="float: left">
          <el-tooltip class="item" effect="dark" content="修改友链" placement="top">
          <el-button type="primary" icon="el-icon-edit" circle  @click="cardPopup(scope.row.id);selectById(scope.row.name)"></el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="删除友链" placement="top">
            <el-button type="danger" icon="el-icon-delete" circle
                       @click="openDeleteConfirm(scope.row.id)"></el-button>
          </el-tooltip>
        </template>

      </el-table-column>

    </el-table>
</template>

<!--添加或修改弹窗-->
<template>
  <div>
    <el-dialog
        append-to-body
        :title = dialogVisibleTitle
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="40%"
        @close="closeDialog('ruleForm')">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">
        <el-form-item label="友链名" prop="name">
          <el-input v-model="ruleForm.name" maxlength="15" show-word-limit clearable
                    style="width: 300px;"></el-input>
        </el-form-item>

        <el-form-item label="友链地址" prop="url">
          <el-input v-model="ruleForm.url"  show-word-limit clearable
                    style="width: 300px;"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm()">提交</el-button>
          <el-button @click="closeDialog('ruleForm')">重置</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>

    </div>
  </template>

    <!--页码-->
    <template>
      <div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 7, 10, 20]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countDate">
        </el-pagination>
      </div>
    </template>

  </div>
</template>

<!--$("input[serch=true]").on("propertychange input change", function() {-->
<!--seach();-->
<!--});-->
<script>
export default {
  data() {
    return {
      ruleForm:{
        id:'',
        name:'',
        url:''
      }, // 添加 / 修改数据集
      input:{
        name:'',
        offset: '',
        count: ''
      }, // 查询条件集
      tableData: [], // 条件查询结果集
      multipleSelection: [], // 批量删除复选框
      optionsSelectEcho:[],       // 分类数据回显
      rules:
          {
            'name': [{required: true,message: '必填字段',trigger: 'blur'}],
          },

      dialogVisible:false, // 弹出框状态【添加 or 修改功能】，默认隐藏
      dialogVisibleTitle:'添加友链',

      currentPage: 1,   // 当前页码
      currentSize: 5,   // 每页展示信息数量
      countDate: 0,     // 条件查询结果集数量

      AddOrSetByLinkId:0,              // 区别方法【添加 ro 修改】
    }
  },
  methods:{

    /**
     * 弹窗：添加业务 OR 修改业务
     */
    cardPopup(linkId) {
      if (linkId === 0) {
        this.AddOrSetByCategoryId = 0;          // 调用添加方法
        this.dialogVisibleTitle = "添加友链"; // 设置弹窗标题
      } else {
        this.dialogVisibleTitle = "修改友链"; // 设置弹窗标题
        this.AddOrSetByLinkId = linkId;     // 调用修改方法
      }
      this.dialogVisible = true;   // 打开弹窗
    },
    /**
     * 业务：添加 OR 修改
     */
    submitForm() {
      let addOrSetData = this.ruleForm;
      if (addOrSetData.name === null || addOrSetData.name === undefined || addOrSetData.name === ''){
        this.$message({type: 'error', message: "友链名不能为空"})
        return;
      }
      if (addOrSetData.url === null || addOrSetData.url === undefined || addOrSetData.url === ''){
        this.$message({type: 'error', message: "地址不能为空"})
        return;
      }

      if (this.AddOrSetByLinkId === 0) {
        console.log("即将向服务器发送【添加友链】请求，参数：{"+
            "name="+addOrSetData.name+"，"+
            "url="+addOrSetData.url+"，"+"}")

        let path = "http://localhost:9090/links/add-new"
        /**
         * 添加分类
         */
        this.axios.post(path, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: "创建成功"
              });
              this.loadLink()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      } else {
        let url ="http://localhost:9090/links/"+this.ruleForm.id+"/update"
        console.log("即将向服务器发送【修改友链】请求，参数：{"+
            "name="+addOrSetData.name+"，"+
            "url="+addOrSetData.url+"，"+
            "}")
        /**
         * 修改分类
         */
        this.axios.post(url, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '修改友链成功!'
              });
              this.optionsSelectEcho=[];
              this.loadLink()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }
      this.closeDialog();
      this.dialogVisible = false;   // 关闭弹窗
    },
    /*通过id查询*/
    selectById(name) {
      this.axios.get("http://localhost:9090/links/get?name="+name).then((response)=> {
        console.log(response)
        this.ruleForm=response.data.data;
      })
    },
    /**
     * 删除方法
     */
    handleDelete(id) {
      console.log('将删除id=' + id + '的分类');
      this.axios.post("http://localhost:9090/links/" + id + "/delete").then((response) => {
        let json = response.data;
        if(json.code == 200){
          this.$message({
            message: '删除友链成功!',
            type: 'success'
          });
        }else {
          this.$message.error(response.data.message);
        }
        this.loadLink();
      })
    },
    /**
     * 删除确认框
     */
    openDeleteConfirm(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(id);
      }).catch(() => {
      });
    },
    /**
     * 复选框
     * @param val
     */
    handleSelectChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 批量删除
     */
    handleDeleteList() {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'info',
          message: '请勾选需要删除的类别'
        });
        return;
      }
      let array = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        array.push(this.multipleSelection[i].id);
      }

      this.$confirm('此操作将永久删除ID为【'+array+'】的用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/links/deleteByIds", array).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.loadLink();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection();
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },
    /**
     * 刷新页面,获取数据
     */
    loadLink:function (){
      console.log('loadLinks');
      let path = "http://localhost:9090/links";
      console.log('url = ' + path);
      this.axios.get(path).then((response) => {
        let json = response.data;
        if(json.code == 200){
          // let list = json.data;
          // for (let i = 0; i < list.length; i++) {
          //   console.log(list[i]);
          // }
          this.tableData = json.data;
        }else {
          this.$message.error(response.data.message);
        }
      });
    },

    /**
     * 业务：根据条件查询分类列表
     */
    listLinksByCondition() {

      this.input.offset = (this.currentPage - 1) * this.currentSize;
      this.input.count = this.currentSize;

      /**
       * 查询满足查询条件的信息数量
       */
      this.axios.post("http://localhost:9090/links/count",this.input).then((response) => {
        this.countDate = response.data;
      })
      /**
       * 查询满足查询条件的分类列表
       */
      this.axios.post("http://localhost:9090/links/listByLinks",this.input).then((response) => {
        this.tableData = response.data;
      })
    },

    /**
     * 清除弹窗数据及遗留效果
     */
    closeDialog(ruleForm) {
      this.ruleForm = {}
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },

    /**
     * 业务：获取分页，每页条数
     * @param val
     */
    handleSizeChange(val) {
      console.log(`当前每页 ${val} 条`);
      this.currentSize = val;
      this.listLinksByCondition();
    },

    /**
     * 业务：获取当前页数
     * @param val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.listLinksByCondition();
    },


    clearSelection() {
      this.store.clearSelection();
    },
  },
  created() {
    //created >>> 已创建,将在mounted, 显示页面之前执行
    this.loadLink();
  },
}
</script>
